package com.imyuanma.qingyun.common.config.security;

import com.imyuanma.qingyun.common.model.response.Result;
import com.imyuanma.qingyun.common.util.JsonUtil;
import com.imyuanma.qingyun.common.util.WebUtil;
import com.imyuanma.qingyun.interfaces.ums.model.LoginSuccess;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 登录成功后处理器
 *
 * @author wangjy
 * @date 2022/07/09 20:53:51
 */
@Component
public class DefaultLoginSuccessHandler implements AuthenticationSuccessHandler {
    private static final Logger logger = LoggerFactory.getLogger(DefaultLoginSuccessHandler.class);

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        logger.info("[登录成功后处理器] 登录成功,用户={},URI={},权限信息={}", request.getParameter("account"), request.getRequestURI(), JsonUtil.toJson(authentication));
        LoginSuccess loginSuccess = null;
        if (authentication.getPrincipal() instanceof UserDetails) {
            UserDetails userDetails = (UserDetails) authentication.getPrincipal();
            loginSuccess = new LoginSuccess(userDetails.getUsername(), "", request.getParameter("redirectTo"));
        }
        WebUtil.write2Response(response, Result.success(loginSuccess));
//        if (WebUtil.isAjaxRequest(request)){
//            //ajax请求
//            WebUtil.write2Response(response, Result.success());
//        } else {
//            String redirectTo = request.getParameter("redirectTo");
//            if (StringUtil.isNotBlank(redirectTo)) {
//                //请求的url
//                response.sendRedirect(redirectTo);
//            }
//        }
    }
}
